package com.example.d10_homework.homework03;

import java.net.*;

public class UDPServer {
    private static final int PORT = 9876; // 端口可以按需更改

    public static void main(String[] args) {
        try (DatagramSocket socket = new DatagramSocket(PORT)) {
            byte[] buffer = new byte[256];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

            while (true) {
                System.out.println("等待数据...");
                socket.receive(packet); // 阻塞直到接收到数据包

                String received = new String(packet.getData(), 0, packet.getLength());
                System.out.println("接收到的数据: " + received);

                String response = received.toUpperCase();
                DatagramPacket replyPacket = new DatagramPacket(
                        response.getBytes(),
                        response.length(),
                        packet.getAddress(),
                        packet.getPort()
                );
                socket.send(replyPacket);
                System.out.println("回复: " + response);

                // 清空缓冲区以备下次接收
                for (int i = 0; i < buffer.length; i++) {
                    buffer[i] = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}